package com.apestech.api.tables;

import com.apestech.api.tables.modul.SeqField;
import com.apestech.formwork.xml.core.NodeVar;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.xml.pub.WriteXml;
import com.apestech.framework.xml.pub.core.ElementUtil;
import org.dom4j.Element;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hup
 * @create 2019-02-15-16:15
 */
public class ScriptInit extends ElementUtil{

    private SqlSession session;

    public ScriptInit(SqlSession session){
        this.session=session;
    }

    public void init() throws Exception {
        ArrayList<String> list=FileUtil.getFieldList(LocalVariable.getRootDir()+"sql"+ File.separator+"script"+File.separator);
        if(list==null || list.size()==0) return;
        int len=list.size();
        for(int i=0; i<len; i++){
            WriteXml xml=new WriteXml();
            xml.setXml(FileUtil.getXmlStr(list.get(i)));
            xml.createXml();
            Element root=xml.getRoot();
            List<?> nlist=root.content();
            int nlen=nlist.size();
            for(int n=0; n<nlen; n++){
                String field=FileUtil.getFileName(list.get(i));
                field=field.substring(0,field.indexOf("."));
                String scalss=nlist.get(n).getClass().getName();
                if(scalss.equals("org.dom4j.tree.DefaultElement")){
                    Element eml = (Element) nlist.get(n);
                    String name=eml.getName().trim();
                    String id=eml.attributeValue("id");
                    switch (name){
                        case "tables": {
                            if(!session.tableExists(id)){
                                session.getForDDL().createTable("script."+field+"."+id);
                            }
                            break;
                        }
                        case "function" : {
                            String text= eml.getText();
                            text=text.replace("\t\t\t","\n\t\t\t");
                            if(!session.functionExists(id)){
                                session.getForDDL().executeDDL(text);
                            }
                            break;
                        }
                        case "seqKey" : {
                            SequenceManage seq=new SequenceManage(session);
                            setSeqKey(eml, seq);
                        }
                    }

                }
            }
        }

    }

    private void setSeqKey(Element eml, SequenceManage seq) throws Exception {
        List<?> list=eml.content();
        int len=list.size();
        for(int i=0; i<len; i++){
            String scalss=list.get(i).getClass().getName();
            if(scalss.equals("org.dom4j.tree.DefaultElement")){
                Element e = (Element) list.get(i);
                String name=e.getName().trim();
                SeqField seqField=new SeqField();
                JSONObject input=getNodeAttr(e).getJSONObject("attrNode");
                seqField.setField(input);
                seqField.setTableId(name);
                seqField.setTableName(session.getForJSON().getTabComment(name));
                SequenceManage.SeqStatu statu=seq.needInit(seqField);
                if(statu.isInit()){
                    seq.createSeq(seqField, true);
                    Object num=getTableId(name);
                    if(num!=null){
                        long n=seq.getNumByFieldValue(seqField, num);
                        if(n>0) seq.setNum(name, n);
                    }
                }
            }
        }
    }

    private Object getTableId(String tabName) throws Exception {
        Table tab=session.getDictTable(tabName);
        String pk=tab.getPkKey().getPkColumn();
        pk=pk.replaceAll(",","||");
        String sql="SELECT MAX("+pk+") AS NUM FROM "+tabName;
        JSONArray qlist=session.getForJSON().query(sql);
        if(qlist.size()==0) return null;
        return qlist.get(0).get("NUM");
    }

}
